package com.yzx.lifeassistants.model.impl;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;

import com.yzx.lifeassistants.bean.OfficeInform;
import com.yzx.lifeassistants.model.IQueryOfficeInfo;
import com.yzx.lifeassistants.model.callback.IQueryOfficeInfoCB;
import com.yzx.lifeassistants.utils.HttpClientUtil;
import com.yzx.lifeassistants.utils.IHttpCallBack;
import com.yzx.lifeassistants.utils.LogcatUtils;

/**
 * @Description: 查询教务处通知详情
 * @author: yzx
 * @time: 2016-3-10 下午10:06:25
 */
public class QueryOfficeInfoImpl implements IQueryOfficeInfo {

	public static final String TAG = "QueryOfficeInfoImpl";
	private IQueryOfficeInfoCB queryCallBack;// 回调

	public QueryOfficeInfoImpl(Context context, IQueryOfficeInfoCB queryCallBack) {
		this.queryCallBack = queryCallBack;
	}

	/**
	 * 
	 * @Description: 查询教务处通知详情
	 */
	@Override
	public void queryOfficeInfo(String url) {
		HttpClientUtil.sendRequestWithGBK(url, null, new IHttpCallBack() {

			@Override
			public void onFinish(String response) {
				LogcatUtils.i(response);
				if (null == response || "".equals(response)) {
					LogcatUtils.e("获取数据失败");
					queryCallBack.queryFailed(IQueryOfficeInfoCB.QUERY_FAILED);
				} else {
					OfficeInform info = new OfficeInform();
					Document doc = Jsoup.parse(response);
					Elements elements = doc.select("div#mainwarp>div#content");
					for (Element element : elements) {
						String title = element.select("h1").text();
						info.setTitle(title);
						String artInfo = element.select("div#artinfo").text();
						info.setDate(artInfo.substring(0,
								artInfo.indexOf("日") + 1));
						String artBody = element.select(
								"div#artbody>div#MyContent").toString();
						LogcatUtils.i("artBody", artBody);
						info.setDetail(artBody);
					}
					if (null == info.getTitle() || "".equals(info.getTitle())
							|| null == info.getDate()
							|| "".equals(info.getDate())
							|| null == info.getDetail()
							|| "".equals(info.getDetail())) {
						LogcatUtils.e("获取数据失败");
						queryCallBack
								.queryFailed(IQueryOfficeInfoCB.QUERY_FAILED);
					} else {
						LogcatUtils.i("获取数据成功");
						queryCallBack.querySuccess(info);
					}
				}
			}

			@Override
			public void onError(Exception e) {
				LogcatUtils.e("获取数据异常");
				if (null != e.getMessage()) {
					LogcatUtils.e(e.getMessage());
				}
				queryCallBack.queryFailed(IQueryOfficeInfoCB.QUERY_ERROR);
			}
		});
	}

}
